import {
  Findjob
} from 'findjob-model.js';
var findjob = new Findjob(); // 实例化找工作模型对象
import {
  User
} from '../../model/user-model.js';
var user = new User();

import {
  Token
} from '../../utils/token.js';
var token = new Token();

import {
  Note
} from '../findworker/note-model.js';
var note = new Note();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 基础配置
    city: wx.getStorageSync('companyinfo').city || '',
    capsuleTop: 0,
    capsuleHeight: 0,
    scrollTop: 0,
    isLoading: false, // 防止重复请求标记

    // 筛选面板状态
    isArea: true,
    isPrice: true,
    isCate: true,
    isType: true,

    // 筛选参数
    areaid: 0,
    priceid: 0,
    cateid: 0,
    typeid: 0,
    areatitle: '',
    pricetitle: '',
    catetitle: '',
    typetitle: '',

    // 列表数据
    joblist: [],
    jobln: 0,
    jobpricelist: [],
    arealist: [],
    jobcatelist: [],
    worktypelist: [],
    curJobcatelistIndex: 1,

    // 分页配置
    page: 1,
    pageSize: 10,
    totalPages: 1,
    loadMore: '', // 加载提示文本
    isShow: false,
  },


  /**
   * 页面滚动监听（仅用于顶部筛选面板自动关闭）
   */
  onPageScroll: function (t) {
    // 滚动时自动关闭所有筛选面板
    if (t.scrollTop <= 145) {
      this.setData({
        isArea: true,
        isPrice: true,
        isCate: true,
        isType: true
      });
    }
    this.setData({
      scrollTop: t.scrollTop
    });
  },

  /**
   * 筛选面板切换
   */
  toSelectType: function () {
    this.setData({
      isType: !this.data.isType,
      isPrice: true,
      isArea: true,
      isCate: true,
      isShow: true
    });
  },

  toSelectPrice: function () {
    this.setData({
      isPrice: !this.data.isPrice,
      isArea: true,
      isCate: true,
      isType: true,
      isShow: true
    });
  },

  toSelectCate: function () {
    this.setData({
      isCate: !this.data.isCate,
      isPrice: true,
      isArea: true,
      isType: true,
      isShow: true
    });
  },

  toSelectArea: function () {
    this.setData({
      isArea: !this.data.isArea,
      isCate: true,
      isPrice: true,
      isType: true,
      isShow: true,
    });
  },

  /**
   * 筛选选项选择
   */
  SelectAreaItem: function (e) {
    const areaid = e.currentTarget.dataset.id;
    const areatitle = e.currentTarget.dataset.title;
    this.setData({
      areaid,
      areatitle,
      isArea: true,
      scrollTop: 16,
      page: 1, // 重置分页
      joblist: [], // 清空列表
      isShow: false,
    }, () => this.getjoblist());
  },

  SelectPriceItem: function (e) {
    const priceid = e.currentTarget.dataset.id;
    const pricetitle = e.currentTarget.dataset.title;
    this.setData({
      priceid,
      pricetitle,
      isPrice: true,
      scrollTop: 16,
      page: 1,
      joblist: [],
      isShow: false,
    }, () => this.getjoblist());
  },

  SelectTypeItem: function (e) {
    const typeid = e.currentTarget.dataset.id;
    const typetitle = e.currentTarget.dataset.title;
    this.setData({
      typeid,
      typetitle,
      isType: true,
      scrollTop: 16,
      page: 1,
      joblist: [],
      isShow: false,
    }, () => this.getjoblist());
  },

  SelectCateItem: function (e) {
    const cateid = e.currentTarget.dataset.id;
    const catetitle = e.currentTarget.dataset.title;
    this.setData({
      cateid,
      catetitle,
      isCate: true,
      scrollTop: 16,
      page: 1,
      joblist: [],
      isShow: false,
    }, () => this.getjoblist());
  },

  /**
   * 跳转职位选择页
   */
  toSelectJob: function () {
    wx.navigateTo({
      url: "/pages/selectjob/index"
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 初始化筛选参数
    const cateid = options.jobcateid ? Number(options.jobcateid) : 0;
    const areaid = options.areaid ? Number(options.areaid) : 0;

    this.setData({
      cateid,
      areaid,
      curJobcatelistIndex: 1
    });

    // 设置导航栏标题
    wx.setNavigationBarTitle({ title: '找工作' });

    // 获取胶囊按钮位置信息
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
    this.setData({
      capsuleTop: menuButtonInfo.top,
      capsuleHeight: menuButtonInfo.height
    });

    // 开启分享功能
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });

    // 初始化页面数据
    this.initPageData();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 页面显示时刷新数据（重置分页并重新加载）
    this.setData({
      page: 1,
      joblist: []
    }, () => this.initPageData());
  },

  /**
   * 初始化页面基础数据（分类、区域等）
   */
  initPageData: function() {
    if (this.data.isLoading) return;
    this.setData({ isLoading: true });

    // 显示加载提示
    wx.showLoading({ title: '加载中...', mask: true });

    // 获取本地存储的城市信息
    const cityinfo = wx.getStorageSync('cityinfo');
    if (cityinfo) {
      wx.setStorageSync('city', cityinfo.name);
      this.setData({ city: cityinfo.name });
    }

    // 构造请求参数
    const params = this.getRequestParams();

    // 调用接口获取基础数据
    findjob.getJobListData((data) => {
      wx.hideLoading();

      // 处理分类默认选中
      const thisCateid = this.data.cateid === 0
        ? (data.jobcatelist[0]?.id || 0)
        : this.data.cateid;
      const targetIndex = this.findIndexById(data.jobcatelist, thisCateid);

      // 更新页面数据
      this.setData({
        jobpricelist: data.jobpricelist || [],
        arealist: data.arealist || [],
        jobcatelist: data.jobcatelist || [],
        worktypelist: data.worktypelist || [],
        curJobcatelistIndex: targetIndex,
        cateid: thisCateid,
        totalPages: data.totalPages || 1,
        isLoading: false
      }, () => {
        // 数据更新后加载职位列表
        wx.nextTick(() => {
          this.getjoblist();
          this.checkMenuItemVisible(targetIndex);
        });
      });

      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    }, params, (err) => {
      // 错误处理
      wx.hideLoading();
      console.error('初始化数据失败:', err);
      this.setData({ isLoading: false });
      wx.showToast({ title: '数据加载失败', icon: 'none' });
    });
  },

  /**
   * 获取职位列表数据（核心分页加载逻辑）
   */
  getjoblist: function () {
    if (this.data.isLoading) return;
    this.setData({ isLoading: true });

    // 判断是否有更多数据
    if (this.data.page > this.data.totalPages) {
      this.setData({
        loadMore: '没有更多数据了',
        isLoading: false
      });
      return;
    }

    // 构造请求参数
    const params = this.getRequestParams();

    // 调用接口获取职位列表
    findjob.getJobListData((data) => {
      // 处理分页数据（拼接新数据）
      const newJobList = this.data.page === 1
        ? data.joblist
        : [...this.data.joblist, ...data.joblist];

      // 更新页面数据
      this.setData({
        joblist: newJobList,
        jobln: newJobList.length,
        totalPages: data.totalPages || 1,
        // 判断是否还有更多数据
        loadMore: newJobList.length < this.data.pageSize * this.data.page
          ? '没有更多数据了'
          : '',
        isLoading: false
      });
    }, params, (err) => {
      // 错误处理
      console.error('获取职位列表失败:', err);
      this.setData({
        loadMore: '加载失败，点击重试',
        isLoading: false
      });
      wx.showToast({ title: '列表加载失败', icon: 'none' });
    });
  },

  /**
   * 构造请求参数（复用逻辑）
   */
  getRequestParams: function () {
    const cityinfo = wx.getStorageSync('cityinfo') || {};
    return {
      cityid: cityinfo.id || 0,
      page: this.data.page,
      pageSize: this.data.pageSize,
      areaid: this.data.areaid,
      priceid: this.data.priceid,
      jobcateid: this.data.cateid,
      latitude: wx.getStorageSync('latitude') || 0,
      longitude: wx.getStorageSync('longitude') || 0,
      type: this.data.typeid
    };
  },

  /**
   * 跳转职位详情页
   */
  toJobDetail: function (e) {
    const id = e.currentTarget.dataset.id;
    var that = this;

    var params = {};

    token.verify(
        user.checkBind((data) => {
          if (data.isbind) {
            var city;
            city = wx.getStorageSync('city');
            var paramsPubNote = {
              city: city
            };
            note.getPubNoteInit((data) => {
              console.log("data", data.noteinfo)
              if (data.noteinfo && data.noteinfo.id) {
                wx.navigateTo({
                  url: "/pages/jobdetail/index?id=" + id
                });
              } else {
                wx.navigateTo({
                  url: "/pages/mynote/index"
                })
              }
            }, paramsPubNote)
          } else {
            wx.navigateTo({
              url: "/pages/register/index"
            })
          }
        }, params)
    )
    // const id = e.currentTarget.dataset.id;
    // wx.navigateTo({
    //   url: "/pages/jobdetail/index?id=" + id
    // });
  },

  /**
   * 职位分类点击事件
   */
  handleItemClick(event) {
    const { id, index } = event.currentTarget.dataset;
    this.setData({
      curJobcatelistIndex: index,
      cateid: id,
      page: 1,
      joblist: []
    }, () => {
      wx.nextTick(() => {
        this.checkMenuItemVisible(index);
        this.getjoblist();
      });
    });
  },

  /**
   * 检查菜单项可见性并滚动到视图
   */
  checkMenuItemVisible(index) {
    const query = wx.createSelectorQuery().in(this);

    query.select('#leftMenu').boundingClientRect(menuRect => {
      if (!menuRect) return;

      query.select(`.menu-item:nth-child(${index + 1})`).boundingClientRect(itemRect => {
        if (!itemRect) return;

        const containerHeight = menuRect.height;
        const itemHeight = itemRect.height;

        // 向上滚动
        if (itemRect.top < menuRect.top) {
          this.setData({ scrollTop: index * itemHeight });
        }
        // 向下滚动
        else if (itemRect.bottom > menuRect.bottom) {
          this.setData({ scrollTop: (index + 1) * itemHeight - containerHeight });
        }
      }).exec();
    }).exec();
  },

  /**
   * 根据ID查找列表索引
   */
  findIndexById(list, id) {
    const index = list.findIndex(item => item.id === id);
    return index !== -1 ? index : 0;
  },

  /**
   * 右侧列表滚动到底部触发（替代页面级onReachBottom）
   */
  onScrollToLower: function() {
    // 正在加载中 或 没有更多数据时，不执行操作
    if (this.data.isLoading || this.data.page >= this.data.totalPages) {
      return;
    }
    // 加载下一页
    this.setData({
      page: this.data.page + 1,
      loadMore: '正在加载更多...'
    }, () => {
      this.getjoblist(); // 调用分页加载方法
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 下拉刷新（页面级）
   */
  onPullDownRefresh: function() {
    this.setData({
      page: 1,
      joblist: []
    }, () => {
      this.initPageData(() => {
        wx.stopPullDownRefresh(); // 停止下拉动画
      });
    });
  },

  /**
   * 页面上拉触底事件（已被scroll-view的onScrollToLower替代，保留兼容）
   */
  onReachBottom() {
    // 兼容处理：如果scroll-view逻辑失效，可临时启用此方法
    // this.onScrollToLower();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '找工作',
      path: '/pages/findjob/index'
    };
  }
});
